package com.zjcode.cdcer.controller;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.consts.Consts.MQ_TYPE;
import com.chinatechstar.component.commons.controller.BaseController;
import com.chinatechstar.component.commons.entity.MqData;
import com.chinatechstar.component.commons.result.ListResult;
import com.chinatechstar.component.commons.result.ResultBuilder;
import com.chinatechstar.component.commons.supports.PageData;
import com.zjcode.cdcer.config.MConsts;
import com.zjcode.cdcer.config.MConsts.SUB_DETAIL;
import com.zjcode.cdcer.config.RabbitMQConfig;
import com.zjcode.cdcer.enums.CommonEnum;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.model.CerDetaildataImportInfo;
import com.zjcode.cdcer.model.CerEndoscopicDiagnosisDetails;
import com.zjcode.cdcer.service.CerDetaildataImportInfoService;
import com.zjcode.cdcer.service.CerEndoscopicDiagnosisDetailsService;
import com.zjcode.cdcer.utils.Utils;
import io.swagger.annotations.ApiOperation;

import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/v1/detaileddatareporting/")
public class CerDetaildataImportInfoController extends BaseController {

    @Autowired
    private CerDetaildataImportInfoService cerDetaildataImportInfoService;
    @Autowired
    private CerEndoscopicDiagnosisDetailsService cerEndoscopicDiagnosisDetailsService;

    @Autowired
    private RabbitTemplate template;

    @PostMapping("getPageData")
    @ApiOperation("获取所有的详细数据信息列表")
    public ListResult<Object> listAllTableData(@RequestBody PageData pageData) {
        return ResultBuilder.buildListSuccess(cerDetaildataImportInfoService.listAllTableData(
            pageData));
    }

    @PostMapping("queryAllExportData")
    @ApiOperation("点击导出按钮，获取所有的详细数据信息列表")
    public JsonObj queryAllExportData(@RequestBody PageData pageData) {
        List<LinkedHashMap<String, Object>> list = cerDetaildataImportInfoService.queryAllExportData(
            pageData);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        return JsonObj.success(map);
    }

    @PostMapping("batchDeletion")
    @ApiOperation("批量删除")
    public JsonObj batchDeletion(@RequestBody PageData pageData) {
        return cerDetaildataImportInfoService.batchDeletion(pageData);
    }

    @PostMapping("oneClickDelete")
    @ApiOperation("一键删除")
    public JsonObj oneClickDelete(@RequestBody PageData pageData) {
        return cerDetaildataImportInfoService.oneClickDelete(pageData);
    }

    @PostMapping("deleteById")
    @ApiOperation("根据主键id删除详细数据")
    public JsonObj deleteById(@RequestBody PageData pageData) {
        String id = (String) pageData.get("id");
        int i = cerDetaildataImportInfoService.deleteById(id);
        if (i > 0) {
            return JsonObj.success("删除成功");
        } else {
            return JsonObj.error("删除失败");
        }
    }

    @GetMapping("findDataById")
    @ApiOperation("根据id获取详细信息")
    public JsonObj findDataById() {
        PageData pageData = getPageData();
        String id = (String) pageData.get("id");
        CerDetaildataImportInfo info = cerDetaildataImportInfoService.findDataById(id);
        List<CerEndoscopicDiagnosisDetails> list = cerEndoscopicDiagnosisDetailsService.findByParentId(
            id);
        if (info != null) {
            String extFlag2 = info.getExtFlag2();
            Map<String, Boolean> map = Utils.parseExtFlag2(extFlag2);
            info.setIsShowSgDetail(map.get(SUB_DETAIL.SG) ? 1 : 0);
            info.setIsShowBmDetail(map.get(SUB_DETAIL.BM) ? 1 : 0);
            info.setIsShowWDetail(map.get(SUB_DETAIL.WD) ? 1 : 0);
            //info.setReportFilePath("");
            //info.setBlReportFilePath("");

            Map<String, Object> data = new HashMap<>();
            Map<String, List<CerEndoscopicDiagnosisDetails>> detailMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(list)) {
                detailMap = list
                    .parallelStream()
                    .collect(Collectors.groupingBy(CerEndoscopicDiagnosisDetails::getObjType));
            }
            data.put(CommonEnum.RESP.getValue(), info);
            data.put("detailMap", detailMap);
            return JsonObj.success(data);
        } else {
            return JsonObj.error("未能获取到对应的数据");
        }
    }

    /**
     * 执行文件解析
     *
     * @param pageData
     * @return
     */
    @PostMapping("execFileParse")
    public JsonObj execFileParse(@RequestBody PageData pageData) {
        String ids = (String) pageData.get("ids");
        String user = (String) pageData.get(MConsts.Common.USER);

        // 发送请求到消息队列进行数据处理
        MqData mqData = new MqData();
        mqData.setTradeNo(user);
        mqData.setContent(ids);
        mqData.setType(MQ_TYPE.PARSE_CER_DETAIL_REPORT_FILE);
        template.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                                RabbitMQConfig.ROUTING_KEY,
                                JSONObject.toJSONString(mqData));

        return JsonObj.success("操作成功");
    }

    /**
     * 更新数据
     *
     * @param pageData
     * @return
     */
    @PostMapping("updateRecord")
    @ApiOperation("更新数据")
    public JsonObj updateRecord(@RequestBody PageData pageData) {

        String json = JSONObject.toJSONString(pageData);

        CerDetaildataImportInfo info = JSONObject.parseObject(json, CerDetaildataImportInfo.class);

        String user = (String) pageData.get(MConsts.Common.USER);
        String tmp = (String) pageData.get(MConsts.Common.SKIP);
        // 是否需要跳过出错提醒
        boolean skip = "1".equals(tmp);

        // 取出原始数据
        CerDetaildataImportInfo detaildataImportInfo = cerDetaildataImportInfoService.findDataById(
            info.getId());
        // 登录用户必须是创建人才能修改数据
        if (!detaildataImportInfo
            .getCreateBy()
            .equals(user)) {
            return JsonObj.error("您无法修改当前记录");
        }

        //内镜诊断详情数据集合
        List<CerEndoscopicDiagnosisDetails> list = new ArrayList<>();

        //得到食管集合数据(sg)
        Object sg = pageData.get(SUB_DETAIL.ESOPHAGUS);
        //得到贲门数据(bm)
        Object bm = pageData.get(SUB_DETAIL.CARDIA);
        //得到胃集合数据(w)
        Object w = pageData.get(SUB_DETAIL.STOMACH);

        // 进行数据验证
        List<String> errors = Utils.validateDetailImportInfoData(info, sg, bm, w);
        //if (errors.size() > 0 && !skip) {
        //    return JsonObj.error(errors
        //                             .stream()
        //                             .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER)));
        //}

        //报告单存放地址
        Object reportFilePath = pageData.get(MConsts.URL.REPORT_PATH);
        //报告单url访问地址
        Object reportFileUrl = pageData.get(MConsts.URL.REPORT_URL);
        //病理报告单存放地址
        Object blReportFilePath = pageData.get(MConsts.URL.PATHOLOGY_PATH);
        //病理报告单url访问地址
        Object blReportFileUrl = pageData.get(MConsts.URL.PATHOLOGY_URL);

        if (ObjectUtils.isNotEmpty(sg)) {
            List<CerEndoscopicDiagnosisDetails> sgList = handleEndoscopicDiagnosisDetails(sg,
                                                                                          MConsts.ENDOSCOPIC_DIAGNOSIS_TYPE.SG,
                                                                                          info.getId(),
                                                                                          detaildataImportInfo.getCreateBy());
            list.addAll(sgList);
        }

        if (ObjectUtils.isNotEmpty(bm)) {
            List<CerEndoscopicDiagnosisDetails> bmList = handleEndoscopicDiagnosisDetails(bm,
                                                                                          MConsts.ENDOSCOPIC_DIAGNOSIS_TYPE.BM,
                                                                                          info.getId(),
                                                                                          detaildataImportInfo.getCreateBy());
            list.addAll(bmList);
        }

        if (ObjectUtils.isNotEmpty(w)) {
            List<CerEndoscopicDiagnosisDetails> wList = handleEndoscopicDiagnosisDetails(w,
                                                                                         MConsts.ENDOSCOPIC_DIAGNOSIS_TYPE.WD,
                                                                                         info.getId(),
                                                                                         detaildataImportInfo.getCreateBy());
            list.addAll(wList);
        }

        if (errors.size() > 0 && !skip) {
            return JsonObj.error(errors
                                     .stream()
                                     .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER)));
        }

        info.setErrorMessage(errors
                                 .stream()
                                 .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER)));

        // 重新赋值原始数据
        updateOriginal(info, detaildataImportInfo);

        if (Objects.nonNull(reportFilePath) && !StringUtils.isEmpty(reportFilePath.toString())) {
            detaildataImportInfo.setReportFilePath(reportFilePath.toString());
        }

        if (Objects.nonNull(reportFileUrl) && !StringUtils.isEmpty(reportFileUrl.toString())) {
            detaildataImportInfo.setReportFileUrl(reportFileUrl.toString());
            detaildataImportInfo.setNjReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_UPLOADED);
        } else {
            detaildataImportInfo.setNjReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_NOT_UPLOAD);
        }

        if (Objects.nonNull(blReportFilePath)
            && !StringUtils.isEmpty(blReportFilePath.toString())) {
            detaildataImportInfo.setBlReportFilePath(blReportFilePath.toString());
        }

        if (Objects.nonNull(blReportFileUrl) && !StringUtils.isEmpty(blReportFileUrl.toString())) {
            detaildataImportInfo.setBlReportFileUrl(blReportFileUrl.toString());
            detaildataImportInfo.setBlReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_UPLOADED);
        } else {
            detaildataImportInfo.setBlReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_NOT_UPLOAD);
        }

        // 更新主表数据
        int updateResult = cerDetaildataImportInfoService.updateRecord(detaildataImportInfo);
        // 删除旧的子表数据
        cerEndoscopicDiagnosisDetailsService.deleteByParentId(info.getId());
        // 插入新的子表数据
        cerEndoscopicDiagnosisDetailsService.batchInsert(list);
        if (updateResult > 0) {
            return JsonObj.success("更新成功");
        } else {
            return JsonObj.error("更新失败");
        }

    }

    /**
     * 重新赋值原始数据
     *
     * @param info
     * @param original
     */
    private void updateOriginal(CerDetaildataImportInfo info, CerDetaildataImportInfo original) {
        original.setMzh(info.getMzh());
        original.setZyh(info.getZyh());
        original.setName(info.getName());
        original.setSex(info.getSex());
        original.setAge(info.getAge());
        original.setPhone(info.getPhone());
        original.setSfz(info.getSfz());
        original.setZlFs(info.getZlFs());
        original.setAddr(info.getAddr());
        original.setNjzlTime(info.getNjzlTime());
        original.setZldxLy(info.getZldxLy());
        original.setNjNum(info.getNjNum());
        original.setAche(info.getAche());
        original.setDye(info.getDye());
        original.setIsHj(info.getIsHj());
        original.setHp(info.getHp());
        original.setHpjcjg(info.getHpjcjg());
        original.setPicNums(info.getPicNums());
        original.setNjStaff(info.getNjStaff());
        original.setVerifyStaff(info.getVerifyStaff());
        original.setNjzd(info.getNjzd());
        original.setBlNum(info.getBlNum());
        original.setBlbgTime(info.getBlbgTime());
        original.setSgblCode(info.getSgblCode());
        original.setBmblCode(info.getBmblCode());
        original.setWblCode(info.getWblCode());
        original.setSezcCode(info.getSezcCode());
        original.setBlzdStaff(info.getBlzdStaff());
        original.setBlshStaff(info.getBlshStaff());
        original.setIsDangerous(info.getIsDangerous());
        original.setNjReportStatus(info.getNjReportStatus());
        original.setBlReportStatus(info.getBlReportStatus());
        original.setReportFilePath(info.getReportFilePath());
        original.setReportFileUrl(info.getReportFileUrl());
        original.setBlReportFilePath(info.getBlReportFilePath());
        original.setBlReportFileUrl(info.getBlReportFileUrl());
        original.setBlzd(info.getBlzd());
        original.setIsHaveError(
            info.getErrorMessage() == null || "".equals(info.getErrorMessage()) ? 0 : 1);
        original.setErrorMessage(info.getErrorMessage() == null ? "" : info.getErrorMessage());
        original.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
    }


    private List<CerEndoscopicDiagnosisDetails> handleEndoscopicDiagnosisDetails(Object obj,
                                                                                 String type,
                                                                                 String id,
                                                                                 String createBy) {
        //转换数据
        String str = obj.toString();
        List<CerEndoscopicDiagnosisDetails> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(str)) {
            int index = 0;
            list = JSONObject.parseArray(str, CerEndoscopicDiagnosisDetails.class);
            list
                .parallelStream()
                .forEach(item -> {
                    //主键
                    item.setId(get32UUID());
                    //关联主键
                    item.setParentId(id);
                    //类型
                    item.setObjType(type);
                    //删除参数
                    item.setDeleted(0);
                    //版本
                    item.setVersion(1);
                    //创建者
                    item.setCreateBy(createBy);
                    //排序
                    item.setSort(String.valueOf(index + 1));
                });
        }
        return list;
    }

}
